import 'package:easy_refresh/easy_refresh.dart';

import '../../../utils/util.dart';

class PageModel<T> {
  int current;
  int total;
  int size;
  int pages;
  List<T>? records;

  bool get hasNext {
    return pages > current;
  }

  PageModel({
    this.current = 1,
    this.total = 1,
    this.size = 10,
    this.pages = 1,
    this.records,
  });

  /// json 整个data
  /// fromJsonT 数据内部列表解析
  /// listKey 当内部列表key 不是默认records时，可自定义
  factory PageModel.fromJson(
    Map<String, dynamic> json,
    T Function(Map<String, dynamic> json) fromJsonT, {
    String currentKey = 'current',
    String listKey = 'records',
    String pageKey = 'pages',
  }) =>
      PageModel<T>(
        current: json[currentKey] as int? ?? 1,
        total: json['total'] as int? ?? 1,
        size: json['size'] as int? ?? 1,
        pages: json['pages'] as int? ?? 1,
        records: (json[listKey] as List?)
            ?.map(
              (e) => fromJsonT(e),
            )
            .toList(),
      );

  void update(NetBaseReponse res, {EasyRefreshController? refreshCtrl}) {
    if (res.data is PageModel) {
      if (res.isSuccess) {
        PageModel page = res.data!;
        current = page.current;
        total = page.total;
        size = page.size;
        pages = page.pages;

        if (page.current > 1) {
          records?.addAll(page.records as List<T>? ?? []);
          if (!page.hasNext) {
            refreshCtrl?.finishLoad(IndicatorResult.noMore);
            return;
          }
          refreshCtrl?.finishLoad();
        } else {
          records = page.records as List<T>?;
          if (page.hasNext) {
            refreshCtrl?.finishLoad();
          } else {
            refreshCtrl?.finishLoad(IndicatorResult.noMore);
          }
          refreshCtrl?.finishRefresh();
        }
      }
    }
  }

  void reset() {
    records = null;
    current = 1;
  }
}
